#!/bin/bash
# Author: <fanyuantao>
# Descripton: This script is used to modify the ssh port of the base model.

currtent_ssh_port=0

function modify_ssh_check() {
    echo ""
    if [[ ! -z $(grep "#Port " /etc/ssh/sshd_config) ]]; then
        echo "SSH port is use default value 22 ."
        currtent_ssh_port=$(grep "#Port " /etc/ssh/sshd_config | awk '{print $2}')
    else
        echo "Current ssh port is $(grep "Port " /etc/ssh/sshd_config | awk '{print $2}')"
        currtent_ssh_port=$(grep "Port " /etc/ssh/sshd_config | awk '{print $2}')
    fi
    echo ""
    read -p "Do you want to modify the ssh port? (y/n) " answer
    if [ "$answer" != "y" ]; then
        echo "Operation cancelled."
        exit 1
    fi
    echo ""
    echo "Willing to modify the ssh port..."
    echo ""
    while true; do
        read -p "Please enter the new ssh port: " port
        if [ -z "$port" ] || [[ $port =~ ^[0-9]+$ ]] || lsof -i :$port > /dev/null; then
            modify_ssh_port $port
            break
        else
            echo "Invalid port or port is already in use."
        fi
    done
}

function modify_ssh_port() {
    echo "Modifying ssh port to $1..."

    if [[ ! -z $(grep "#Port " /etc/ssh/sshd_config) ]]; then 
        sed -i "s/#Port $currtent_ssh_port/Port $1/g" /etc/ssh/sshd_config
    else
        sed -i "s/Port $currtent_ssh_port/Port $1/g" /etc/ssh/sshd_config
    fi

    # 检测当前服务器的防火墙类型，并进行相应的端口放行
    if [ -f /etc/firewalld/zones/public.xml ]; then
        # 检测当前防火墙状态，如果没打开则开启
        if systemctl status firewalld | grep -q "inactive"; then
            systemctl start firewalld
        fi
        firewall-cmd --zone=public --remove-port=$currtent_ssh_port/tcp --permanent -q
        firewall-cmd --zone=public --add-port=$1/tcp --permanent -q
        firewall-cmd --reload
    fi
    systemctl restart sshd
    echo "ssh port has been modified to $1"
}

function main() {
    modify_ssh_check
}

main